package com.luli.entity;

/**
 * 陆离
 * 2024/12/10
 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DatabaseUtil {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "root";

    public static List<Department> getAllDepartments() {
        List<Department> departments = new ArrayList<>();
        try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement statement = connection.prepareStatement("SELECT id as departmentId, name as departmentName, parent_id as parentDepartmentId FROM tree")) {
            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                int departmentId = resultSet.getInt("departmentId");
                String departmentName = resultSet.getString("departmentName");
                int parentDepartmentId = resultSet.getInt("parentDepartmentId");
                Department department = new Department(departmentId, departmentName, parentDepartmentId);
                departments.add(department);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return departments;
    }
}
